#include <iostream>
#include <vector>
#include <algorithm>

#include "sqlfield.h"
#include "character.h"



int sql_field_trans_in_like(
  const std::string& input,
  std::vector<sql_field_character>& output,
  std::string escape,
  CHARSET_E ch) 
{
  std::vector<std::string> splited;
  int len = split_character(input, splited, ch);
  if (len <= 0) {
    return -1;
  }

  int stat = 0; // 0: 没在转义 1: 转义中
  std::for_each(splited.begin(), splited.end(), [&](std::string& str) {
    if (stat) {
      output.push_back(sql_field_character(str, sql_field_class::DATA));
      stat = 0;
    } else if (str == escape) {
      output.push_back(sql_field_character(str, sql_field_class::ESCAPE));
      stat = 1;
    } else if (str == "%") {
      output.push_back(sql_field_character(str, sql_field_class::PERCENT));
    } else if (str == "_") {
      output.push_back(sql_field_character(str, sql_field_class::UNDERLINE));
    } else {
      output.push_back(sql_field_character(str, sql_field_class::DATA));
    }
  });
  return output.size();
}


int sql_field_trans_in_insert(
  const std::string& input,
  std::vector<sql_field_character>& output,
  CHARSET_E ch) 
{
  std::vector<std::string> splited;
  int len = split_character(input, splited, ch);
  if (len <= 0) {
    return -1;
  }

  std::for_each(splited.begin(), splited.end(), [&](std::string& str) {
    output.push_back(sql_field_character(str, sql_field_class::DATA));
  });
  return output.size();
}

std::string sql_field_build_in_like(
  std::vector<sql_field_character>& input,
  std::string escape) 
{
  std::string str;

  int first = 1;
  std::for_each(input.begin(), input.end(), [&](sql_field_character& character){
    switch (character.getClass()) {
      case sql_field_class::DATA:
        if (!first) {
          str.append("|");
        } else {
          first = 0;
        }
        str.append(character.getData());
        break;
      case sql_field_class::ESCAPE:
        break;
      case sql_field_class::PERCENT:
        str.append("%");
        break;
      case sql_field_class::UNDERLINE:
        str.append("_");
        break;
    }
  });

  return str;
}

std::string sql_field_build_in_insert(
  std::vector<sql_field_character>& input)
{
  std::string str;

  int first = 1;
  std::for_each(input.begin(), input.end(), [&](sql_field_character& character){
    if (!first) {
      str.append("|");
    } else {
      first = 0;
    }
    str.append(character.getData());
  });
  return str;
}

